﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.Core.Security
{
    public static class AesEncryption
    {
        private static readonly byte[] iv = new byte[16];
        private static readonly string DefaultKey = "default";

        private static byte[] HashKey(string encryptKey)
        {
            return SHA256.HashData(Encoding.UTF8.GetBytes(encryptKey));
        }

        public static string EncryptKey { get; private set; } = DefaultKey;

        public static void SetEncryptKey(string encryptKey)
        {
            EncryptKey = encryptKey;
        }

        public static string Encrypt(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentException("加密文本为空", nameof(plainText));

            using Aes aes = Aes.Create();
            aes.Key = HashKey(EncryptKey);
            aes.IV = iv;

            using ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
            using MemoryStream ms = new();
            using (CryptoStream cs = new(ms, encryptor, CryptoStreamMode.Write))
            using (StreamWriter sw = new(cs))
            {
                sw.Write(plainText);
            }
            return Convert.ToBase64String(ms.ToArray());
        }

        public static string Decrypt(string cipherText)
        {
            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentException("解密文本为空.", nameof(cipherText));

            try
            {
                using Aes aes = Aes.Create();
                aes.Key = HashKey(EncryptKey);
                aes.IV = iv;

                using ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
                using MemoryStream ms = new(Convert.FromBase64String(cipherText));
                using CryptoStream cs = new(ms, decryptor, CryptoStreamMode.Read);
                using StreamReader sr = new(cs);
                return sr.ReadToEnd();
            }
            catch (CryptographicException e)
            {
                Console.WriteLine($"解密异常: {e.Message}");
                throw new InvalidOperationException("解密失败", e);
            }
        }
    }

}
